package com.example.test1.account;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/accounts")
public class AccountController {

    @Autowired
    private AccountRepository accountRepository;

    // 添加账户
    @PostMapping
    public ResponseEntity<Account> createAccount(@Valid @RequestBody Account account, BindingResult bindingResult) {
       
    
        if (accountRepository.findById(account.getId()).isPresent()) {
            
            return new ResponseEntity<>(null, HttpStatus.CONFLICT);
        }

        accountRepository.save(account);


        return new ResponseEntity<>(account, HttpStatus.CREATED);
    }

    // 更新账户余额
    @PutMapping("/{id}/balance")
    public ResponseEntity<Void> updateBalance(@PathVariable Long id, @RequestParam double newBalance) {
        
        if (newBalance < 0) {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }

        accountRepository.updateBalance(id, newBalance);

    
        return ResponseEntity.ok().build();
    }

    
}